package com.yaodian100.ec.activity.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.UUID;

import org.apache.commons.lang.time.FastDateFormat;

import com.yaodian100.core.common.exception.CoreException;
import com.yaodian100.core.common.service.impl.DomainServiceImpl;
import com.yaodian100.core.common.utils.DateUtil;
import com.yaodian100.ec.activity.entity.ActivityPage;
import com.yaodian100.ec.activity.service.ActivityPageService;
import com.yaodian100.ec.common.EcConstant;

public class ActivityPageServiceImpl extends DomainServiceImpl<ActivityPage> implements ActivityPageService {

	/* (non-Javadoc)
	 * @see com.yaodian100.ec.activity.service.ActivityPageService#uploadMainVisualImage(java.io.File)
	 */
	@Override
	public String uploadMainVisualImage(File imageFile) throws CoreException {
		String today = FastDateFormat.getInstance(EcConstant.DEFAULT_PATTERN_DATE).format(DateUtil.getToday().getTime());
		String path = today + "/" + this.getImageFileName();
		File dest = new File(MAIN_VISUAL_IMAGE_PATH + File.separator + path);
		dest.getParentFile().mkdirs();
		
		FileOutputStream out = null;
		FileInputStream in = null;
		try {
			out = new FileOutputStream(dest);
			in = new FileInputStream(imageFile);
			byte[] b = new byte[256];
			while (in.read(b) != -1) {
				out.write(b);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new CoreException("ActivityPageService:"+e.getMessage(),e);
		} finally {
			try {
				in.close();
			} catch (Exception e) {}
			try {
				out.close();
			} catch (Exception e) {}
		}
		
		return path;
	}
	
	private String getImageFileName() {
		return UUID.randomUUID().toString().replaceAll("-", "") + ".jpg";
	}
	
}
